package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbSellerMapper;
import com.dongdongshop.model.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.util.ShiroUtils;
import com.dongdongshop.vo.SellerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private TbSellerMapper tsm;

    @Override
    public SellerVO sellerByName(String sellerId) {
        TbSeller tbSeller = tsm.selectByPrimaryKey(sellerId);
        SellerVO sellerVO = new SellerVO();
        BeanUtils.copyProperties(tbSeller,sellerVO);
        return sellerVO;
    }

    @Override
    public void sellerAdd(SellerVO sellerVO) throws Exception {
        TbSeller tb = new TbSeller();
        BeanUtils.copyProperties(sellerVO,tb);
        //查询是否有重复的sellerId
        TbSeller tbSeller = tsm.selectByPrimaryKey(tb.getSellerId());
        if (tbSeller != null){
            throw new Exception();
        }
        //如果没有重复的sellerId, 则将密码加密, 并增加
        String password = tb.getPassword();
        String s = ShiroUtils.generateSalt(6);
        String md5 = ShiroUtils.encryptPassword("MD5", password, s, 5);
        tb.setPassword(md5);
        tb.setSalt(s);
        tsm.insertSelective(tb);
    }

    @Override
    public List<SellerVO> sellerAll() {
        List<TbSeller> sellerList = tsm.selectByExample(null);
        List<SellerVO> voList = sellerList.stream().map(tbSeller -> {
            SellerVO sellerVO = new SellerVO();
            BeanUtils.copyProperties(tbSeller, sellerVO);
            return sellerVO;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public void updateStatus(String id, int status) {
        TbSeller tbSeller = tsm.selectByPrimaryKey(id);
        if (status == 1){
            tbSeller.setStatus("1");
        }else if (status == 2){
            tbSeller.setStatus("2");
        } else if (status == 3){
            tbSeller.setStatus("3");
        }
        tsm.updateByPrimaryKeySelective(tbSeller);
    }
}
